<template>
  <div class="login-container">
    <div class="login-card">
      <div class="logo-area">
        <img src="../assets/logo.png" alt="Music OCR Logo" class="logo" />
        <h1>音乐识别助手</h1>
      </div>
      
      <h2>登录</h2>
      
      <form @submit.prevent="login">
        <div class="input-group">
          <label for="username">用户名</label>
          <input 
            type="text" 
            id="username" 
            v-model="username" 
            placeholder="请输入用户名或邮箱"
            required
          />
        </div>
        
        <div class="input-group">
          <label for="password">密码</label>
          <input 
            type="password" 
            id="password" 
            v-model="password" 
            placeholder="请输入密码"
            required
          />
        </div>
        
        <div class="remember-me">
          <input type="checkbox" id="remember" v-model="rememberMe" />
          <label for="remember">记住我</label>
        </div>
        
        <button type="submit" class="login-btn" :disabled="isLoading">
          {{ isLoading ? '登录中...' : '登录' }}
        </button>
        
        <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>
        
        <div class="register-link">
          还没有账号？ <router-link to="/register">立即注册</router-link>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { API_BASE_URL } from '../config';

export default {
  name: 'LoginView',
  data() {
    return {
      username: '',
      password: '',
      rememberMe: false,
      isLoading: false,
      errorMessage: ''
    }
  },
  methods: {
    async login() {
      // 验证表单
      if (!this.username || !this.password) {
        this.errorMessage = '请输入用户名和密码';
        return;
      }
      
      this.isLoading = true;
      this.errorMessage = '';
      
      try {
        // 发起登录请求 - 使用正确的认证API路径
        const response = await axios.post(`${API_BASE_URL}/auth/login`, {
          username: this.username,
          password: this.password,
          remember_me: this.rememberMe
        });
        
        if (response.data && response.data.access_token) {
          // 处理登录成功
          console.log('登录成功:', response.data);
          
          // 创建完整的用户信息对象，包含token
          const user = {
            ...response.data.user,
            access_token: response.data.access_token
          };
          
          // 存储用户信息和token
          localStorage.setItem('user', JSON.stringify(user));
          // 同时单独存储token，确保与App.vue中的检查兼容
          localStorage.setItem('token', response.data.access_token);
          
          // 触发登录成功事件
          this.emitUserLoginEvent();
          
          // 检查是否有待处理的帖子ID（在访问帖子详情页时需要登录的情况）
          const pendingPostId = localStorage.getItem('pending_post_id');
          
          // 重定向到首页或预期的跳转页面
          const redirect = this.$route.query.redirect || '/';
          
          if (pendingPostId) {
            console.log('检测到待处理的帖子ID:', pendingPostId);
            
            // 直接导航到社区页面的帖子详情
            this.$router.push('/community');
          } else {
            console.log('重定向到:', redirect);
            // 检查redirect是否是完整URL(包含http或https协议)
            if (redirect.startsWith('http://') || redirect.startsWith('https://')) {
              // 如果是完整URL，使用window.location进行导航
              console.log('检测到完整URL，使用window.location重定向');
              window.location.href = redirect;
            } else {
              // 如果是相对路径，使用Vue Router导航
              console.log('使用Vue Router导航到:', redirect);
              this.$router.push(redirect);
            }
          }
        } else {
          this.errorMessage = '登录失败，请检查用户名和密码';
        }
      } catch (error) {
        // 处理登录错误
        console.error('登录错误:', error);
        
        if (error.response) {
          // 服务器返回了错误状态码
          if (error.response.status === 401) {
            this.errorMessage = '用户名或密码错误';
          } else {
            this.errorMessage = error.response.data.detail || '登录失败，请稍后再试';
          }
        } else if (error.request) {
          // 请求发出但没有收到响应
          this.errorMessage = '服务器无响应，请检查网络连接';
        } else {
          // 设置请求时发生的错误
          this.errorMessage = '登录请求错误，请稍后再试';
        }
      } finally {
        this.isLoading = false;
      }
    },
    
    emitUserLoginEvent() {
      // 使用全局事件
      const event = new CustomEvent('user-login-success');
      window.dispatchEvent(event);
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.dark-theme .login-container {
  background: linear-gradient(135deg, #121212 0%, #1e1e24 100%);
}

.login-card {
  width: 100%;
  max-width: 450px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  padding: 40px;
}

.dark-theme .login-card {
  background: var(--card-bg);
  box-shadow: var(--card-shadow);
}

.logo-area {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  width: 80px;
  height: 80px;
  object-fit: contain;
}

h1 {
  font-size: 24px;
  color: #333;
  margin: 10px 0 0;
}

.dark-theme h1 {
  color: #ffffff;
}

h2 {
  font-size: 20px;
  color: #333;
  margin-bottom: 20px;
  text-align: center;
}

.dark-theme h2 {
  color: #ffffff;
}

.input-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 5px;
  color: #555;
  font-size: 14px;
}

.dark-theme label {
  color: #cccccc;
}

input[type="text"],
input[type="password"] {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
  color: #333;
  background: white;
  transition: border 0.3s ease, box-shadow 0.3s ease;
}

.dark-theme input[type="text"],
.dark-theme input[type="password"] {
  background: var(--input-bg);
  border-color: var(--input-border);
  color: var(--input-text);
}

input[type="text"]:focus,
input[type="password"]:focus {
  border-color: #4f46e5;
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.2);
  outline: none;
}

.dark-theme input[type="text"]:focus,
.dark-theme input[type="password"]:focus {
  border-color: var(--input-focus-border);
  box-shadow: 0 0 0 3px var(--input-focus-shadow);
}

.remember-me {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.remember-me input {
  margin-right: 8px;
}

.login-btn {
  width: 100%;
  padding: 12px;
  background: #4361ee;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.3s ease, transform 0.2s ease;
}

.login-btn:hover {
  background: #3a0ca3;
  transform: translateY(-2px);
}

.login-btn:disabled {
  background: #a0a0a0;
  cursor: not-allowed;
  transform: none;
}

.error-message {
  color: #e53e3e;
  margin-top: 15px;
  text-align: center;
  font-size: 14px;
}

.register-link {
  margin-top: 20px;
  text-align: center;
  font-size: 14px;
  color: #555;
}

.dark-theme .register-link {
  color: #aaaaaa;
}

.register-link a {
  color: #4361ee;
  text-decoration: none;
  font-weight: 600;
}

.register-link a:hover {
  text-decoration: underline;
}
</style> 